<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectModel;
use app\app\model\RandModel;
use app\BaseController;
use app\app\model\ProjectCheckModel;
use app\Request;
use PhpOffice\PhpSpreadsheet\Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Filesystem;


class ProjectCheck extends BaseController
{
    public function list()
    {
        $project_name = input('project_name','');
        $issue_level = input('issue_level','');
        $zg_flag = input('zg_flag','');


        $page_size = input('pageSize', '20');

        $where = [];
        if ($project_name) {
            $where[] = ['project_name', 'like', '%' . $project_name . '%'];
        }
        if ($issue_level) {
            $where[] = ['issue_level', '=', $issue_level];
        }
        if ($zg_flag) {
            $where[] = ['zg_flag', '=', $zg_flag];
        }

        $list = ProjectCheckModel::where($where)->paginate([
            'list_rows'=> $page_size,
            'var_page' => 'pageNum',
        ]);
        $this->success('success', $list);
    }

    public function add(Request $request)
    {
        $data = $request->param();
        $model = new ProjectCheckModel();
        $data['oper_time'] = date('Y-m-d H:i:s', time());
        $result = $model->save($data);
        if ($result !== false) {
            $this->success('添加成功!');
        } else {
            $this->error("保存失败！");
        }
    }

    public function update(Request $request)
    {
        $data = $request->param();
        $id = $request->param('id', 0, 'intval');
        $result = ProjectCheckModel::strict(false)->where('id', $id)->update($data);
        if ($result !== false) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }


    public function delete(Request $request)
    {
        $data = $request->param();
        $ids = $data['ids'];
        ProjectCheckModel::destroy(function ($query) use ($ids) {
            $query->where('id', 'in', $ids);
        });
    }

    /**
     * 监理问题导入
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function import()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate([
                'file' => 'filesize:52428800|fileExt:xls,xlsx'
            ])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'check', $file['file']);

        $data = (new FileImport())->ExcelImport($file_path . $file_name);

        $insert_array = [];
        $error_array = [];
        $i = 0;

        foreach ($data as $k => $v) {
            $i++;

            if ($k == 0) continue;
            if (empty($v[0])) continue;

            $project = ProjectModel::where('project_name', $v[0])
                ->where('is_parent', 1)
                ->find();
            if (empty($project)) {
                $error_array[] = '第' . $i .  '行项目名称异常';
                continue;
            }

            $project_id = $project->id;

            $insert_array[] = [
                'id' => RandModel::randId(),
                'project_id' => $project_id,
                'check_time' => FileImport::excelDateParse($v[7]),
                'check_type' => 2,
                'check_photo_id' => '',
                'check_file_id' => null,
                'check_content' => $v[18] ?: '',
                'check_av_id' => null,
                'project_lz_id' => null,
                'check_duration' => null,
                'check_source' => '监理检查',
                'check_user' => $v[10],
                'issue_level' => $v[15] ?: '',
                'peccancy_id' => 0,
                'fk_money' => '',
                'zrr_name' => $v[21] ?: '',
                'project_name' => $v[0],
                'zg_flag' => null,
                'state' => 2,
                'file_path' => '',
            ];
        }
        (!empty($error_array)) && $this->error('上传异常：' . implode('，', $error_array));

        try {
            (new ProjectCheckModel())->insertAll($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }
}
